import { BaseGraph, IBaseProps, IBoundBox } from './base'

export interface IText extends IBaseProps {
  text: string
}

export class Text extends BaseGraph {
  private _text: string = ''
  private _canvas = document.createElement('canvas')
  private _ctx = this._canvas.getContext('2d')
  private _width = 0
  private _height = 0
  private _top = 0
  private _left = 0
  constructor(props: IText) {
    super(props)
    this.type = 'text'
    this._text = props?.text || this._text
  }
  public setPath() {
    delete this.path
    this.path = new Path2D()
    this.initStyle(this._ctx)
    let measure = this._ctx.measureText(this._text)
    this._width = measure.actualBoundingBoxRight
    this._height = measure.fontBoundingBoxAscent + measure.fontBoundingBoxDescent
    this._left = -measure.actualBoundingBoxLeft
    this._top = -measure.fontBoundingBoxAscent
    this.path.rect(this._left, this._top, this._width, this._height)
  }
  drawPath(ctx: CanvasRenderingContext2D): void {
    ctx.fillStyle = 'rgba(0,0,0,0)'
    ctx.fill(this.path)
    ctx.fillStyle =
      typeof this.defaultOption.fillStyle == 'string'
        ? this.defaultOption.fillStyle
        : this.defaultOption.fillStyle.get()
    if (this.isFill) ctx.fillText(this.text, 0, 0)
    else ctx.strokeText(this.text, 0, 0)
  }
  public set text(value: string) {
    this._text = value
  }
  public get text() {
    return this._text
  }
  public clone() {
    return new Text({ ...this.option, ...this.getBaseCloneAttr(), text: this._text })
  }
  public getBoundBox(): IBoundBox {
    return {
      top: this._top,
      bottom: this._top + this._height,
      left: this._left,
      right: this._left + this._width,
      width: this._width,
      height: this._height
    }
  }
}
